package com.cencat.order.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cencat.order.entity.OrderInfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 订单信息Mapper接口
 * 
 * @author cencat
 * @since 2024-01-20
 */
@Mapper
public interface OrderInfoMapper extends BaseMapper<OrderInfo> {

    /**
     * 分页查询订单列表
     * 
     * @param page 分页参数
     * @param userId 用户ID
     * @param merchantId 商家ID
     * @param orderStatus 订单状态
     * @param paymentStatus 支付状态
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 订单分页列表
     */
    @Select("<script>" +
            "SELECT * FROM order_info WHERE deleted = 0" +
            "<if test='userId != null'> AND user_id = #{userId}</if>" +
            "<if test='merchantId != null'> AND merchant_id = #{merchantId}</if>" +
            "<if test='orderStatus != null'> AND order_status = #{orderStatus}</if>" +
            "<if test='paymentStatus != null'> AND payment_status = #{paymentStatus}</if>" +
            "<if test='startTime != null'> AND create_time >= #{startTime}</if>" +
            "<if test='endTime != null'> AND create_time <= #{endTime}</if>" +
            " ORDER BY create_time DESC" +
            "</script>")
    IPage<OrderInfo> selectOrderPage(Page<OrderInfo> page,
                                   @Param("userId") Long userId,
                                   @Param("merchantId") Long merchantId,
                                   @Param("orderStatus") Integer orderStatus,
                                   @Param("paymentStatus") Integer paymentStatus,
                                   @Param("startTime") LocalDateTime startTime,
                                   @Param("endTime") LocalDateTime endTime);

    /**
     * 根据订单号查询订单
     * 
     * @param orderNo 订单号
     * @return 订单信息
     */
    @Select("SELECT * FROM order_info WHERE order_no = #{orderNo} AND deleted = 0")
    OrderInfo selectByOrderNo(@Param("orderNo") String orderNo);

    /**
     * 批量更新订单状态
     * 
     * @param orderIds 订单ID列表
     * @param orderStatus 订单状态
     * @param updateBy 更新人
     * @return 更新数量
     */
    @Update("<script>" +
            "UPDATE order_info SET order_status = #{orderStatus}, update_by = #{updateBy}, update_time = NOW()" +
            " WHERE id IN" +
            "<foreach collection='orderIds' item='id' open='(' separator=',' close=')'>" +
            "#{id}" +
            "</foreach>" +
            " AND deleted = 0" +
            "</script>")
    int batchUpdateOrderStatus(@Param("orderIds") List<Long> orderIds,
                              @Param("orderStatus") Integer orderStatus,
                              @Param("updateBy") String updateBy);

    /**
     * 更新支付状态
     * 
     * @param orderId 订单ID
     * @param paymentStatus 支付状态
     * @param paymentMethod 支付方式
     * @param paidAmount 实付金额
     * @param updateBy 更新人
     * @return 更新数量
     */
    @Update("UPDATE order_info SET payment_status = #{paymentStatus}, payment_method = #{paymentMethod}, " +
            "paid_amount = #{paidAmount}, payment_time = NOW(), update_by = #{updateBy}, update_time = NOW() " +
            "WHERE id = #{orderId} AND deleted = 0")
    int updatePaymentStatus(@Param("orderId") Long orderId,
                           @Param("paymentStatus") Integer paymentStatus,
                           @Param("paymentMethod") String paymentMethod,
                           @Param("paidAmount") BigDecimal paidAmount,
                           @Param("updateBy") String updateBy);

    /**
     * 更新物流信息
     * 
     * @param orderId 订单ID
     * @param shippingStatus 物流状态
     * @param logisticsCompany 物流公司
     * @param logisticsNo 物流单号
     * @param updateBy 更新人
     * @return 更新数量
     */
    @Update("UPDATE order_info SET shipping_status = #{shippingStatus}, logistics_company = #{logisticsCompany}, " +
            "logistics_no = #{logisticsNo}, shipping_time = NOW(), update_by = #{updateBy}, update_time = NOW() " +
            "WHERE id = #{orderId} AND deleted = 0")
    int updateShippingInfo(@Param("orderId") Long orderId,
                          @Param("shippingStatus") Integer shippingStatus,
                          @Param("logisticsCompany") String logisticsCompany,
                          @Param("logisticsNo") String logisticsNo,
                          @Param("updateBy") String updateBy);

    /**
     * 取消订单
     * 
     * @param orderId 订单ID
     * @param cancelReason 取消原因
     * @param updateBy 更新人
     * @return 更新数量
     */
    @Update("UPDATE order_info SET order_status = 5, cancel_reason = #{cancelReason}, cancel_time = NOW(), " +
            "update_by = #{updateBy}, update_time = NOW() WHERE id = #{orderId} AND deleted = 0")
    int cancelOrder(@Param("orderId") Long orderId,
                   @Param("cancelReason") String cancelReason,
                   @Param("updateBy") String updateBy);

    /**
     * 完成订单
     * 
     * @param orderId 订单ID
     * @param updateBy 更新人
     * @return 更新数量
     */
    @Update("UPDATE order_info SET order_status = 4, completion_time = NOW(), " +
            "update_by = #{updateBy}, update_time = NOW() WHERE id = #{orderId} AND deleted = 0")
    int completeOrder(@Param("orderId") Long orderId, @Param("updateBy") String updateBy);

    /**
     * 统计订单数量（按状态）
     * 
     * @param userId 用户ID（可选）
     * @param merchantId 商家ID（可选）
     * @param startTime 开始时间（可选）
     * @param endTime 结束时间（可选）
     * @return 状态统计结果
     */
    @Select("<script>" +
            "SELECT order_status, COUNT(*) as count FROM order_info WHERE deleted = 0" +
            "<if test='userId != null'> AND user_id = #{userId}</if>" +
            "<if test='merchantId != null'> AND merchant_id = #{merchantId}</if>" +
            "<if test='startTime != null'> AND create_time >= #{startTime}</if>" +
            "<if test='endTime != null'> AND create_time <= #{endTime}</if>" +
            " GROUP BY order_status" +
            "</script>")
    List<Map<String, Object>> countByStatus(@Param("userId") Long userId,
                                           @Param("merchantId") Long merchantId,
                                           @Param("startTime") LocalDateTime startTime,
                                           @Param("endTime") LocalDateTime endTime);

    /**
     * 计算订单总金额
     * 
     * @param userId 用户ID（可选）
     * @param merchantId 商家ID（可选）
     * @param orderStatus 订单状态（可选）
     * @param startTime 开始时间（可选）
     * @param endTime 结束时间（可选）
     * @return 总金额
     */
    @Select("<script>" +
            "SELECT COALESCE(SUM(total_amount), 0) FROM order_info WHERE deleted = 0" +
            "<if test='userId != null'> AND user_id = #{userId}</if>" +
            "<if test='merchantId != null'> AND merchant_id = #{merchantId}</if>" +
            "<if test='orderStatus != null'> AND order_status = #{orderStatus}</if>" +
            "<if test='startTime != null'> AND create_time >= #{startTime}</if>" +
            "<if test='endTime != null'> AND create_time <= #{endTime}</if>" +
            "</script>")
    BigDecimal sumTotalAmount(@Param("userId") Long userId,
                             @Param("merchantId") Long merchantId,
                             @Param("orderStatus") Integer orderStatus,
                             @Param("startTime") LocalDateTime startTime,
                             @Param("endTime") LocalDateTime endTime);

    /**
     * 查询待处理订单列表
     * 
     * @param merchantId 商家ID（可选）
     * @return 待处理订单列表
     */
    @Select("<script>" +
            "SELECT * FROM order_info WHERE deleted = 0 AND order_status IN (0, 1, 2)" +
            "<if test='merchantId != null'> AND merchant_id = #{merchantId}</if>" +
            " ORDER BY create_time ASC" +
            "</script>")
    List<OrderInfo> selectPendingOrders(@Param("merchantId") Long merchantId);

    /**
     * 查询已完成订单列表
     * 
     * @param userId 用户ID（可选）
     * @param merchantId 商家ID（可选）
     * @param limit 限制数量
     * @return 已完成订单列表
     */
    @Select("<script>" +
            "SELECT * FROM order_info WHERE deleted = 0 AND order_status = 4" +
            "<if test='userId != null'> AND user_id = #{userId}</if>" +
            "<if test='merchantId != null'> AND merchant_id = #{merchantId}</if>" +
            " ORDER BY completion_time DESC" +
            "<if test='limit != null'> LIMIT #{limit}</if>" +
            "</script>")
    List<OrderInfo> selectCompletedOrders(@Param("userId") Long userId,
                                         @Param("merchantId") Long merchantId,
                                         @Param("limit") Integer limit);
}